<?php


namespace app\openwx\controller;

use app\common\library\wechat\WxBizMsgCrypt;
use Endroid\QrCode\QrCode;
use think\Db;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Log;
use think\facade\Request;
use app\common\library\Openssl;
use Qiniu\Auth as qiniuauth;
use Qiniu\Storage\BucketManager;
use Qiniu\Config as QiniuConfig;
use Qiniu\Storage\UploadManager;
use app\common\library\Qiniu;

class Auth extends Base
{
    public function subscribe()
    {
        $openssl = new Openssl();
        $data = $openssl->decrypt(input('param.token'));
        $new_data = \Qiniu\json_decode($data, true);
        if ($new_data['expires_in'] < time()) {
            $this->assign('info', 'TOKEN超时-10002');
            return view('/work/error');
        }
        $info = DB::name('product_wx')->where('product_run_id', $new_data['id'])->find();
        $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $info['authorizer_access_token'].'&openid='.$new_data['openid'].'&lang=zh_CN';
        $data2=[];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $tmpInfo = curl_exec($ch);
        $re = json_decode($tmpInfo, TRUE);
        if (isset($re['subscribe']) && $re['subscribe']) {
            return $re['subscribe'];
        }else{
            return 3;
        }
    }
    //获取微信公众号二维码，有id,直接获取，没有id通过传入的域名
    public function wxqrcode()
    {
        $openssl = new Openssl();
        $data = $openssl->decrypt(input('param.token'));
        $new_data = \Qiniu\json_decode($data, true);
        if ($new_data['expires_in'] < time()) {
            $this->assign('info', 'TOKEN超时-10002');
            return view('/work/error');
        }
        //dump($data);
        if(isset($new_data['domain']) && $new_data['domain']){
$new_data['id']= DB::name('product_run')
    ->where('domain|diy_domain', $new_data['domain'])
    ->where('e_time', '>=', time())
    //->cache(43200)//约12小时
    ->value('id');
        }
        //dump($new_data);
        //exit;


        $info = DB::name('product_wx')->where('product_run_id', $new_data['id'])->find();
        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $info['authorizer_access_token'];
        $data2=[];
        $data2['action_name'] = 'QR_LIMIT_STR_SCENE';
        $data2['expire_seconds'] = 86400;
        $data2['action_info'] ['scene']['scene_str'] = '项目管理平台';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data2));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $tmpInfo = curl_exec($ch);
        $re = json_decode($tmpInfo, TRUE);
        if (isset($re['ticket']) && $re['url']) {
            $imgurl ='https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$re['ticket'];
            echo $imgurl;
        }
    }

    /**
     * 异步通知处理
     */
    public function base_auth_code()
    {
        $openssl = new Openssl();
        $data = $openssl->decrypt(input('param.token'));
        $new_data = \Qiniu\json_decode($data, true);
        if ($new_data['expires_in'] < time()) {
            $this->assign('info', 'TOKEN超时-10002');
            return view('/work/error');
        }
        //dump($id);
        $url = url('/auth/auth_code?token=' . input('param.token'), '', '', 'openwx.weibuyun.com');
        $this->assign('url', $url);
        //
        $info = $this->get_info($new_data['id']);
        $info['industry'] = $this->get_industry($new_data['id']);
        $info['template'] = $this->get_template($new_data['id']);
        $info['url_industry'] = url('/auth/set_industry?token=' . input('param.token'), '', '', 'openwx.weibuyun.com');
        $info['url_template'] = url('/auth/set_template?token=' . input('param.token'), '', '', 'openwx.weibuyun.com');

        $this->assign('info', $info);
        return view();
    }

    public function set_industry()
    {
        $openssl = new Openssl();
        $data = $openssl->decrypt(input('param.token'));
        $new_data = \Qiniu\json_decode($data, true);
        if ($new_data['expires_in'] < time()) {
            $this->error('TOKEN超时-11001');

        }
        $info = db::name('product_wx')->where('product_run_id', $new_data['id'])->find();
        if ($info) {

        } else {
            return false;
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=' . $info['authorizer_access_token'];
        $data['template_id_short'] = 'OPENTM200559613';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $tmpInfo = curl_exec($ch);
        $re = json_decode($tmpInfo, TRUE);

        if (isset($re['errcode'])) {
            if ($re['errcode'] == 0) {
                return '模板设置成功';
            }
            return '模板，设置失败，请到公众号中设置添加，标题为：项目进度提醒，编号：OPENTM200559613';
        } else {
            //信息错误
            return false;
        }

    }

    public function set_template()
    {
        $openssl = new Openssl();
        $data = $openssl->decrypt(input('param.token'));
        $new_data = \Qiniu\json_decode($data, true);
        if ($new_data['expires_in'] < time()) {
            $this->error('TOKEN超时-11001');

        }
        $info = db::name('product_wx')->where('product_run_id', $new_data['id'])->find();
        if ($info) {

        } else {
            return false;
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=' . $info['authorizer_access_token'];
        $data['template_id_short'] = 'OPENTM200559613';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $tmpInfo = curl_exec($ch);
        $re = json_decode($tmpInfo, TRUE);

        if (isset($re['errcode'])) {
            if ($re['errcode'] == 0) {
                return '模板设置成功';
            }
            return '模板，设置失败，请到公众号中设置添加，标题为：项目进度提醒，编号：OPENTM200559613';
        } else {
            //信息错误
            return false;
        }

    }

    public function get_template($id)
    {
        $info = db::name('product_wx')->where('product_run_id', $id)->find();
        if ($info) {

        } else {
            return false;
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=' . $info['authorizer_access_token'];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $tmpInfo = curl_exec($ch);
        $re = json_decode($tmpInfo, TRUE);

        if (isset($re['template_list'])) {
            foreach ($re['template_list'] as $info) {
                if ($info['template_id'] == 'GL8nE9UMfONHXXd_tNECLHEX7folE2vFUT1faPthybI') {
                    return '模板设置正确';
                }
            }
            return '模板不适合，请重设';
        } else {
            //信息错误
            return false;
        }

    }

    public function get_industry($id)
    {
        $info = db::name('product_wx')->where('product_run_id', $id)->find();
        if ($info) {

        } else {
            return false;
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=' . $info['authorizer_access_token'];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $tmpInfo = curl_exec($ch);
        $re = json_decode($tmpInfo, TRUE);
        //dump($re);
        if (isset($re['primary_industry'])) {
            if ($re['primary_industry']['first_class'] == 'IT科技' && $re['primary_industry']['second_class'] == 'IT软件与服务') {
                return '行业设置正确';
            }
            if ($re['secondary_industry']['first_class'] == 'IT科技' && $re['secondary_industry']['second_class'] == 'IT软件与服务') {
                return '行业设置正确';
            }
            return '行业设置错误，请重新设置';
        } else {
            //信息错误
            return false;
        }

    }


    public function get_info($id)
    {
        $info = db::name('product_wx')->where('product_run_id', $id)->find();
        //dump($info);
        if ($info) {

        } else {
            return false;
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=' . cache('component_access_token');
        $data['component_appid'] = config('param.component_appid');
        $data['authorizer_appid'] = $info['authorizer_appid'];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $tmpInfo = curl_exec($ch);
        $re = json_decode($tmpInfo, TRUE);
        if (isset($re['authorizer_info'])) {
            switch ($re['authorizer_info']['verify_type_info']['id']) {
                case -1:
                    $re['authorizer_info']['verify_type_info'] = '未认证';
                    break;
                case 0:
                    $re['authorizer_info']['verify_type_info'] = '微信认证';

                    break;
                case 1:
                    $re['authorizer_info']['verify_type_info'] = '新浪微博认证';
                    break;
                case 2:
                    $re['authorizer_info']['verify_type_info'] = '腾讯微博认证';
                    break;
                case 3:
                    $re['authorizer_info']['verify_type_info'] = '已资质认证通过但还未通过名称认证';
                    break;
                case 4:
                    $re['authorizer_info']['verify_type_info'] = '已资质认证通过、还未通过名称认证，但通过了新浪微博认证';
                    break;
                case 5:
                    $re['authorizer_info']['verify_type_info'] = '已资质认证通过、还未通过名称认证，但通过了腾讯微博认证';
                    break;
                default:
                    $re['authorizer_info']['verify_type_info'] = '不明';
            }
            switch ($re['authorizer_info']['service_type_info']['id']) {
                case 0:
                    $re['authorizer_info']['service_type_info'] = '订阅号';
                    break;
                case 1:
                    $re['authorizer_info']['service_type_info'] = '由历史老帐号升级后的订阅号';
                    break;
                case 2:
                    $re['authorizer_info']['service_type_info'] = '服务号';
                    break;

                default:
                    $re['authorizer_info']['service_type_info'] = '不明';
            }
            db::name('product_wx')->where('product_run_id', $id)->update(['appid' => $re['authorizer_info']['user_name']]);
            return $re['authorizer_info'];
        } else {
            //信息错误

        }

    }

    public function post2()
    {
        Log::write('==', 'ERROR');

        Log::write(input('post.'), 'ERROR');
        echo '=========';
        dump(Request::param(false));
    }

    public function auth_code()
    {
        if (input('?token')) {
            $openssl = new Openssl();
            $data = $openssl->decrypt(input('param.token'));
            $new_data = \Qiniu\json_decode($data, true);
            if ($new_data['expires_in'] < time()) {
                $this->assign('info', 'TOKEN超时-10002');
                return view('/work/error');
            }

            if (DB::name('product_run')->where('id', $new_data['id'])->find()) {
                if (DB::name('product_wx')->where('product_run_id', $new_data['id'])->find()) {
                    $this->assign('info', '已经存在微信绑定信息-10004');
                } else {
                    // echo 1;
                }
            } else {
                $this->assign('info', '项目错误-10003');
                return view('work/error');
            }
        } else {
            $this->assign('info', '参数错误-10000');
            return view('work/error');
        }
        //dump(config());

        if (cache('component_access_token')) {

            $url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=' . cache('component_access_token');
            $data2['component_appid'] = config('param.component_appid');
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data2));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            $tmpInfo = curl_exec($ch);
            $re = json_decode($tmpInfo, TRUE);
            if (isset($re['pre_auth_code'])) {
                $url = url('/auth/re_auth_code?id=' . $new_data['id'], '', '', 'openwx.weibuyun.com');
                // dump($url);
                // exit;
                $nurl = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=' . config('param.component_appid') . '&pre_auth_code=' . $re['pre_auth_code'] . '&redirect_uri=' . $url . '&auth_type=3';
                $this->redirect($nurl);
            } else {
                //信息错误
                $this->assign('info', '请联系平台技术进行解决-10001');
                return view('work/error');
            }
        } else {
            //token错误
            $this->assign('info', '请联系平台技术进行解决-10002');
            return view('work/error');
        }

    }

    public function re_auth_code()
    {
        if (input('?id')) {
            if (DB::name('product_run')->where('id', input('param.id'))->find()) {

                $url = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=' . cache('component_access_token');
                $data['component_appid'] = config('param.component_appid');
                $data['authorization_code'] = input('param.auth_code');
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 30);
                $tmpInfo = curl_exec($ch);
                $re = json_decode($tmpInfo, TRUE);
                if (isset($re['authorization_info'])) {
                    DB::name('product_wx')->where('product_run_id', input('param.id'))->delete();
                    $item['product_run_id'] = input('param.id');
                    $item['authorizer_appid'] = $re['authorization_info']['authorizer_appid'];
                    $item['authorizer_access_token'] = $re['authorization_info']['authorizer_access_token'];
                    $item['authorizer_refresh_token'] = $re['authorization_info']['authorizer_refresh_token'];
                    $item['update_time'] = time();
                    $item['qrcode'] = $this->wx_qrcode($item['authorizer_access_token'], $item['authorizer_access_token']);
                    $product_wx_id = DB::name('product_wx')->insertGetId($item);
                    if ($product_wx_id) {
                        $this->assign('info', '绑定成功-10015');
                        return view();
                    } else {
                        $this->assign('info', '信息保存出错-10014');
                        return view('work/error');
                    }

                } else {
                    //信息错误
                    $this->assign('info', '微信错误-10013');
                    return view('work/error');
                }


            } else {
                $this->assign('info', '信息不存在-10012');
                return view('work/error');
            }
        }


    }

}